package com.changgou.order.controller;

import com.changgou.core.helper.RequestUtil;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljh
 * @version 1.0
 * @date 2021/1/5 11:58
 * @description 标题
 * @package com.changgou.order.controller
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加购物成功
     *
     * @param num 购买的数量
     * @param id  购买的sku的ID
     * @return
     */
    @RequestMapping("/add")
    public Result add(Integer num, Long id) {

        //解析令牌中的user_name的值该值就是登录用户名
        String username = RequestUtil.getUserName();

        cartService.add(num, id, username);
        return new Result(true, StatusCode.OK, "购买成功");
    }

    @RequestMapping("/list")
    public Result<List<OrderItem>> list() {
        //获取登录的用户名
        String username = RequestUtil.getUserName();
        //根据用户名查询该用户对应的购物车的列表
        List<OrderItem> cartList = cartService.list(username);
        return new Result(true, StatusCode.OK, "查询成功", cartList);
    }
    //优化之后 购物车代码===============================start============================
    //添加购物车
    @GetMapping("/addx")
    public Result addx(Integer num,Long id){
        //获取用户名
        String username = RequestUtil.getUserName();
        //添加购物车
        cartService.addToRedis(num,id,username);
        return Result.ok();
    }

    //删除购物车商品
    @DeleteMapping("/deletex")
    public Result deletex(Long id){
        //获取用户名
        String username = RequestUtil.getUserName();
        //删除购物车
        cartService.deletex(id,username);
        return Result.ok();
    }

    //更新购物车数量
    @GetMapping("/updatex")
    public Result udpatex(Long id,Integer num){
        //获取用户名
        String username = RequestUtil.getUserName();
        //添加购物车
        cartService.updatex(num,id,username);
        return Result.ok();
    }


    /**
     * 获取购物车列表
     * @return
     */
    @GetMapping("/cartList")
    public Result<List<OrderItem>> cartList(){
        String username = RequestUtil.getUserName();
        List<OrderItem> orderItemList=cartService.listx(username);
        return  Result.ok(orderItemList);
    }




    //============================优化之后购物车代码======================================
}
